package com.kgcx.common.mqtt;

import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author 袁进勇
 */
@Configuration
@ConditionalOnProperty(prefix = "kgcx.mqtt", name = "enable", havingValue = "true")
public class MqttConfig {
    private static final Logger LOG = LoggerFactory.getLogger(MqttConfig.class);

    @Value("${kgcx.mqtt.url:tcp://120.78.159.128:1883}")
    private String url;

    @Value("${kgcx.mqtt.username:kgcx_price}")
    private String userName;

    @Value("${kgcx.mqtt.password:kgcx@123}")
    private String passWord;

    @Value("${kgcx.mqtt.cleanSession:true}")
    private Boolean cleanSession;

    @Value("${kgcx.mqtt.connectionTimeout:10}")
    private Integer connectionTimeout;

    @Value("${kgcx.mqtt.keepAliveInterval:20}")
    private Integer keepAliveInterval;

    @Value("${kgcx.mqtt.automaticReconnect:true}")
    private Boolean automaticReconnect;

    @Bean(name = "mqttProducer")
    public MqttClient mqttProducer(MqttCallback mqttProducerCallback) throws Exception {
        MqttConnectOptions options = new MqttConnectOptions();
        options.setCleanSession(cleanSession);
        options.setUserName(userName);
        options.setPassword(passWord.toCharArray());
        options.setConnectionTimeout(connectionTimeout); // 设置超时时间
        options.setKeepAliveInterval(keepAliveInterval); // 设置会话心跳时间
        options.setAutomaticReconnect(automaticReconnect); // 设置自动重连

        MqttClient client = new MqttClient(url, "P-" + System.currentTimeMillis(), new MemoryPersistence());
        client.setCallback(mqttProducerCallback);

        try {
            client.connect(options);
            return client;
        } catch (MqttException e) {
            LOG.error("创建MQTT连接失败！", e);
            throw new Exception("创建MQTT连接失败！", e);
        }
    }
}
